package edu.sjsu.cs.queryopt.dbms.main;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class ErrorChecking {
	
	static AccessTypeOne ato = new AccessTypeOne();
	
	public boolean IsAssginSameType(ArrayList<String> conditionpod) throws IOException{
		String fronttype = "";
		String backtype = "";
		
	for(int index = 0 ; index < conditionpod.size() ; index++){
			
			if(conditionpod.get(index).trim().equals("=")){
				if(conditionpod.get(index-1).startsWith("T")&& conditionpod.get(index+1).startsWith("T")){
					if(getTypeFromTable(conditionpod.get(index-1)).equals("smalltable")){
						return false;
					}
					else{
						fronttype = getTypeFromTable(conditionpod.get(index-1));
					}
					if(getTypeFromTable(conditionpod.get(index+1)).equals("smalltable")){
						return false;
					}
					else{
						backtype = getTypeFromTable(conditionpod.get(index+1));
					}
					if(backtype.charAt(0) != fronttype.charAt(0)){
						System.err.println("ERROR(IsAssginSameType) : " + "FROM TYPE IS " +fronttype + "  BACK TYPE IS " +  backtype  +
								" It doesn't match the type ");
						return false;
					}
				}
				else if(!conditionpod.get(index-1).startsWith("T") &&conditionpod.get(index+1).startsWith("T") ){
					System.err.println("ERROR(IsAssginSameType) : constant value value " + conditionpod.get(index-1) + " can't be left hand side");
						return false;
				}
				else if(conditionpod.get(index-1).startsWith("T") &&!conditionpod.get(index+1).startsWith("T")){
					if(getTypeFromTable(conditionpod.get(index-1)).length() >1){
					int charlen = conditionpod.get(index+1).length();
					int tableCharlen = Integer.parseInt(getTypeFromTable(conditionpod.get(index-1)).substring(1));
					if(charlen > tableCharlen){
						System.err.println("ERROR(IsAssginSameType) : Length of char " + conditionpod.get(index+1) +" is" + " longer than columen size : " +tableCharlen );
					}
					return false;
					}
				}
			
			}
			
		}
		return true;
		
	}
	public String getTypeFromTable(String TABLEcolName) throws IOException{
		
		BufferedReader br = new BufferedReader(new FileReader(ato.getTableName(TABLEcolName)+".tab"));
		String line = "";
		int tracker = 0 ;
  		while((line = br.readLine()) != null){
  			
  			if(tracker == 0){
  				break;
  			}
  			tracker++;
  		}
  		
  		ArrayList <String> returnAl = new ArrayList<String>();
		String[] tokens = line.trim().split(" ");
    	returnAl.addAll(Arrays.asList(tokens));
    	int colnumer =  Integer.parseInt(ato.getColNumer(TABLEcolName.trim()).trim());
    	if(returnAl.size() < colnumer){
    		System.err.println("ERROR(getTypeFromTable): " + "table size is " + returnAl.size() + " but a user tires to select colume  " + colnumer );
    		return "smalltable";
    		
    	}
		return returnAl.get((colnumer-1));
	}
	

	

}
